package com.xinyue.center.service;

import com.mygame.common.model.AccountToken;
import com.mygame.common.utils.GameTimeUtil;
import com.mygame.common.utils.JWTUtil;
import com.xinyue.center.dao.AccountDao;
import com.xinyue.center.dao.entity.Account;
import com.xinyue.center.dao.redis.EnumRedisKey;
import com.xinyue.center.errorcode.EnumErrorCode;
import com.xinyue.center.messages.request.LoginParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AccountService implements IAccountService {

    @Autowired
    private AccountDao accountDao;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private Logger logger = LoggerFactory.getLogger(AccountService.class);

    /**
     * 根据用户名和密码登陆
     *
     * @param loginParam
     * @return
     * @author wgs
     * @date 2019年8月29日 下午8:24:29
     */
    @Override
    public Optional<Account> login(LoginParam loginParam) throws Exception {
        String userName = loginParam.getUserName();
        String accountId = accountDao.useranmeGenerateAccountId(userName);
        Optional<Account> accountOp = accountDao.getAccountById(accountId);
        if (accountOp.isPresent()) {
            Account account = accountOp.get();
            // 需要添加密码的加密 TODO
            if (account.getPassword().equals(loginParam.getPassword())) {
                logger.debug("user {} 登陆成功", loginParam.getUserName());
                return accountOp;
            } else {
                //返回登陆异常
                throw EnumErrorCode.PASSWORD_ERROR.newException("登陆账号:{}", loginParam.getUserName());
            }
        } else {
            throw EnumErrorCode.ACCOUNT_NOT_EXIST.newException("登陆账号:{}", loginParam.getUserName());
        }
    }

    @Override
    public Account register(LoginParam loginParam) {
        String userName = loginParam.getUserName();
        String accountId = accountDao.useranmeGenerateAccountId(userName);
        Account account = new Account();
        account.setAccountId(accountId);
        account.setUsername(loginParam.getUserName());
        account.setPassword(loginParam.getPassword());
        account.setRegisterIP(loginParam.getLoginIp());
        account.setCreateTime(GameTimeUtil.currentTimeSecond());
        long playerId = this.generatePlayerId();
        account.setPlayerId(playerId);
        accountDao.saveOrUpdate(account, accountId);
        logger.info("{} 注册成功", loginParam.getUserName());
        return account;
    }

    private long generatePlayerId() {
        return redisTemplate.opsForValue().increment(EnumRedisKey.PlayerUUID.getKey());
    }

    @Override
    public String createUserToken(Account account) {
        AccountToken accountToken = new AccountToken();
        accountToken.setAccountId(account.getAccountId());
        accountToken.setPlayerId(account.getPlayerId());
        accountToken.updateExpireDays(30);
        return JWTUtil.createToken(accountToken);
    }

    @Override
    public Account selectAccount(String accountId) {
        return accountDao.findByIdFromCacheOrLoader(accountId).orElse(null);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.saveOrUpdate(account, account.getAccountId());
    }


}
